<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="选择分类" prop="type">
        <el-select
          @change="handleQuery"
          v-model="queryParams.type"
          placeholder="选择分类"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_runescape_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:hairRunescape:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:hairRunescape:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:hairRunescape:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:hairRunescape:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="hairRunescapeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="" align="center" prop="id" v-if="true"/>-->
      <el-table-column label="缩略图1" align="center" prop="thumbnail">
        <template #default="scope">
          <ImagePreview
            v-if="checkFileSuffix(scope.row.fileSuffix)"
            :width="100" :height="100"
            :src="scope.row.thumbnail"
            :preview-src-list="[scope.row.thumbnail]"/>

          <video
            controls
            muted
            :width="200" :height="200"
            v-if="checkVedioFileSuffix(scope.row.fileSuffix)"
            type="video/mp4" :src="scope.row.thumbnail">
          </video>

        </template>
      </el-table-column>
      <!--      <el-table-column label="详情内容" align="center" prop="content" />-->
      <el-table-column label="所属模块" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="sys_runescape_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:hairRunescape:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:hairRunescape:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改江湖对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form
        ref="hairRunescapeRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="选择分类" prop="type">
          <el-select
            v-model="form.type"
            placeholder="选择分类"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in sys_runescape_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

<!--        <el-form-item label="文件类型" prop="type1">-->
<!--          <el-select-->
<!--            v-model="form.type1"-->
<!--            placeholder="选择分类"-->
<!--            clearable-->
<!--            style="width: 240px"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="dict in sys_runescape_type1"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="缩略图" prop="thumbnail">
          <image-uploads v-model="form.thumbnail" limit="1"></image-uploads>
        </el-form-item>
        <el-form-item label="详情内容">
         <video-upload v-model="form.content"></video-upload>
        </el-form-item>
        <el-form-item label="显示状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶" prop="isTop">
          <el-select v-model="form.isTop" placeholder="请选择">
            <el-option
              v-for="dict in sys_yes_or_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HairRunescape">
import {
  listHairRunescape,
  getHairRunescape,
  delHairRunescape,
  addHairRunescape,
  updateHairRunescape,
} from "@/api/business/hairRunescape";
import ImageUploads from "@/components/ImageUploads/index.vue";

const { proxy } = getCurrentInstance();
const { sys_runescape_type, sys_yes_or_no, sys_normal_disable } = proxy.useDict(
  "sys_runescape_type",
  "sys_yes_or_no",
  "sys_normal_disable"
);
import { ref } from "vue";
import VideoUpload from "@/components/VideoUpload/index.vue";
const hairRunescapeList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sys_runescape_type1 = ref([
  { value: 1, label: "图片" },
  { value: 2, label: "视频" },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    thumbnail: undefined,
    content: undefined,
    status: undefined,
    isTop: undefined,
    type: undefined,
    orderNum: undefined,
  },
  rules: {
    id: [{ required: true, message: "不能为空", trigger: "blur" }],
    thumbnail: [{ required: true, message: "缩略图不能为空", trigger: "blur" }],
    content: [{ required: true, message: "详情内容不能为空", trigger: "blur" }],
    status: [
      { required: true, message: "帖子状态不能为空", trigger: "change" },
    ],
    isTop: [
      {
        required: true,
        message: "是否置顶：0：否，1：是不能为空",
        trigger: "blur",
      },
    ],
    type: [
      {
        required: true,
        message:
          "分类：1：素人改造，2：头皮效果，3：在线设计，4：不剃发hot，5：武林秘籍，6：极客侠不能为空",
        trigger: "change",
      },
    ],
    orderNum: [
      { required: true, message: "显示顺序不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询江湖列表 */
function getList() {
  loading.value = true;
  listHairRunescape(queryParams.value).then((response) => {
    hairRunescapeList.value = response.rows;
    total.value = response.total;
    console.log(response.rows)
    for (let i = 0; i < response.rows.length; i++) {
      console.log(response.rows[i])
      let bannerManagerListKey = response.rows[i]
      if(bannerManagerListKey.thumbnail && typeof bannerManagerListKey.thumbnail === 'string'){
        // 获取 URL 的文件名部分
        const filename = bannerManagerListKey.thumbnail.substring(bannerManagerListKey.thumbnail.lastIndexOf('/') + 1);
        console.log(bannerManagerListKey.thumbnail)
        console.log(filename)
        // 使用正则表达式匹配文件后缀名
        const extension = filename.match(/\.[^.]*$/);
        if (extension) {
          // 提取文件后缀名（不包括点）
          const fileExtension = extension[0];
          // 打印文件后缀名
          response.rows[i].fileSuffix = fileExtension;
        } else {
          // URL 没有文件后缀名
          console.log('URL 没有文件后缀名');
        }
      }
    }
    loading.value = false;
  });
}

function checkFileSuffix(fileSuffix) {
  let arr = ["png", "jpg", "jpeg"];
  return arr.some(type => {
    return fileSuffix.indexOf(type) > -1;
  });
}

function checkVedioFileSuffix(fileSuffix) {
  let arr = ["mp4", "avi", "rmvb", "rm"];
  return arr.some(type => {
    return fileSuffix.indexOf(type) > -1;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    thumbnail: null,
    content: null,
    status: "0",
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    isTop: "0",
    type: null,
    type1: 1,
    orderNum: 1,
    delFlag: null,
  };
  proxy.resetForm("hairRunescapeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加江湖";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true;
  reset();
  const _id = row.id || ids.value;
  getHairRunescape(_id).then((response) => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改江湖";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["hairRunescapeRef"].validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateHairRunescape(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addHairRunescape(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除江湖编号为"' + _ids + '"的数据项？')
    .then(function () {
      loading.value = true;
      return delHairRunescape(_ids);
    })
    .then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/hairRunescape/export",
    {
      ...queryParams.value,
    },
    `hairRunescape_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
